package com.tianji.learning.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author Waker
 * @description:
 * @create 2025-10-23-11:42
 */
@Data
@NoArgsConstructor
@AllArgsConstructor(staticName = "of")
public class DelayTask<D> implements Delayed {

    // 延时执行时间的纳秒值
    private Long deadLineNanos;
    // 延时任务的数据
    private D data;

    public DelayTask(Duration duration, D data) {
        this.deadLineNanos = System.nanoTime() + duration.toNanos();
        this.data = data;
    }

    public static <D> DelayTask<D> of(Duration duration, D data) {
        return new DelayTask<>(duration, data);
    }

    /**
     * 1、用来获取队列中每个任务距离当前时间还有多久被执行
     * @param unit the time unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(deadLineNanos - System.nanoTime(),0),TimeUnit.NANOSECONDS);
    }

    /**
     * 2、对延时任务队列中的任务进行排序 （排序依据，根据getDelay方法获取的任务延时时间进行排序、值越小、越先执行）
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        long diff = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return diff > 0 ? 1 : diff < 0 ? -1 : 0;
    }
}
